<script>
export default {

  data() {
    return {
      sentence: '',
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    }
  }, created() {
    this.getSentence()
    window.addEventListener('storage', this.handleStorageChange);

  },
  beforeDestroy() {
    window.removeEventListener('storage', this.handleStorageChange);
  },
  methods: {
    getSentence() {
      this.request.get('/sentence/findById')
          .then(res => {
            this.sentence = res.sentence.sentence
          })
    },
    exit() {
      this.$router.push("/login")
      localStorage.removeItem("user")
      localStorage.removeItem("token")
      this.$message.success("退出成功")
    },
    goPerson() {
      this.$router.push("/person")
    },
    goUpdatePassword() {
      this.$router.push("/updatePassword")

    },
    handleStorageChange(event) {
      if (event.key === 'user') {
        // 用户信息在localStorage发生变化时的处理逻辑
        this.getMyInfo(); // 重新获取用户信息的方法
      }
    },
    getMyInfo() {
      // 假设你有一个方法来从localStorage获取最新的用户信息并更新视图
      const userInfo = JSON.parse(localStorage.getItem("user"));
      if (userInfo) {
        // 更新你的数据以反映最新的用户信息
        this.user = userInfo;
        console.log(user.nickName)
      }
    }
  }
}
</script>

<template>
  <div style="font-size: 20px; display: flex; justify-content: space-between;">
    <div style="display: flex; justify-content: center; flex-grow: 1">
      <h5 style="text-align: center">{{ sentence }}</h5>
    </div>
    <img :src="user.avatar" style="width: 40px;height: 40px;border-radius: 20px;margin-top: 10px;margin-right: 5px"
         alt="">
    <el-dropdown>
      <span>{{ user.nickName || 'admin' }}</span>
      <i class="el-icon-arrow-down" style="margin-left: 10px"></i>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item>
          <span @click="goPerson">
            个人信息</span>
        </el-dropdown-item>
        <el-dropdown-item>
          <span @click="goUpdatePassword">修改密码</span>
        </el-dropdown-item>
        <el-dropdown-item>
          <span @click="exit">退出登录</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<style>

</style>